package weibo.common.exception;


import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import weibo.common.result.JsonResult;
import weibo.common.result.StatusCode;

import javax.validation.ConstraintViolationException;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {
    // 全局异常处理机制
    /*
    将异常包装成一个RuntimeException 抛出给框架 ，由框架统一处理
    * */

    // 处理RuntimeException
    @ExceptionHandler
    public JsonResult doHandleRuntimeException(RuntimeException e) {
        log.error(e.getMessage(),e);
        return new JsonResult(StatusCode.OPERATION_FAILED);
    }

    // 处理Validation 框架抛出的验证未通过异常
    @ExceptionHandler
    public JsonResult doHandleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        String message= e.getFieldError().getDefaultMessage();
        log.error(message,e);
        return new JsonResult(StatusCode.VALIDATE_ERROR,message);
    }
    // 处理Validation  抛出的ConstraintViolationException
    @ExceptionHandler
    public JsonResult doHandleConstraintViolationException(ConstraintViolationException e) {
        String message=e.getMessage();
        message=message.substring(message.indexOf(":")+1).trim();
        log.error(message,e);
        return new JsonResult(StatusCode.VALIDATE_ERROR,message);
    }
    // 处理Throwable 异常 处理未知错误
    @ExceptionHandler
    public JsonResult doHandleThrowable(Throwable e) {
        log.error(e.getMessage(),e);
        return new JsonResult(StatusCode.UNKNOWN_ERROR);
    }

}
